using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using XamarinApp.Droid.Models;

namespace XamarinApp.Droid
{
	public class MyListAdapter : BaseAdapter<ListItemModel>
	{
		private readonly List<ListItemModel> _items;
		private readonly Activity _context;

		public MyListAdapter(Activity context, List<ListItemModel> items)
			: base()
		{
			_context = context;
			_items = items;
		}

		public override long GetItemId(int position)
		{
			return position;
		}

		public override View GetView(int position, View convertView, ViewGroup parent)
		{
			var item = _items[position];
			View view = convertView ?? _context.LayoutInflater.Inflate(Resource.Layout.ListItem, null);

			view.FindViewById<TextView>(Resource.Id.headingText).Text = item.Title;
			view.FindViewById<TextView>(Resource.Id.excerptText).Text = item.Excerpt;
			var imageBitmap = GetImageBitmapFromUrl(item.FeaturedImage);
			view.FindViewById<ImageView>(Resource.Id.featuredImage).SetImageBitmap(imageBitmap);

			return view;
		}

		public override int Count
		{
			get { return _items.Count; }
		}

		public override ListItemModel this[int position]
		{
			get { return _items[position]; }
		}

		private Bitmap GetImageBitmapFromUrl(string url)
		{
			Bitmap imageBitmap = null;

			using (var webClient = new WebClient())
			{
				var imageBytes = webClient.DownloadData(url);
				if (imageBytes != null && imageBytes.Length > 0)
				{
					imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
				}
			}

			return imageBitmap;
		}
	}
}